package com.older.wptsb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.older.wptsb.config.RabbitMQConfig;
import com.older.wptsb.domain.dto.HealthDataDTO;
import com.older.wptsb.domain.dto.SosDTO;
import com.older.wptsb.domain.po.AlertLog;
import com.older.wptsb.domain.po.Elder;
import com.older.wptsb.domain.po.HealthData;
import com.older.wptsb.domain.po.User;
import com.older.wptsb.mapper.CommunityElderMapper;
import com.older.wptsb.mapper.ElderMapper;
import com.older.wptsb.mapper.HealthDataMapper;
import com.older.wptsb.mapper.UserMapper;
import com.older.wptsb.service.ElderService;
import com.older.wptsb.util.UserContext;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class ElderServiceImpl extends ServiceImpl<ElderMapper, HealthData> implements ElderService {

    @Autowired
    private HealthDataMapper healthDataMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private CommunityElderMapper communityElderMapper;

    @Autowired
    private UserMapper userMapper;


    @Override
    public void addElderHealthData(HealthDataDTO healthDataDTO) {
        // 转换DTO到实体类
        HealthData healthData = new HealthData();
        BeanUtils.copyProperties(healthDataDTO, healthData);
        healthData.setElderId(String.valueOf(healthDataDTO.getElderId()));
        String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        healthData.setCreateTime(currentTime);

        // 检查各项指标并设置预警等级
        AlertCheckResult alertCheckResult = checkHealthData(healthDataDTO);
        healthData.setAlertLevel(alertCheckResult.getAlertLevel());

        // 保存到Redis，保留最近的20条记录
        String redisKey = "health_data:" + healthDataDTO.getElderId();
        redisTemplate.opsForList().leftPush(redisKey, healthData);
        redisTemplate.opsForList().trim(redisKey, 0, 19); // 只保留最近20条记录

        // 保存到数据库，每个老人只保留一条最新记录
        String elderId = String.valueOf(healthDataDTO.getElderId());
        List<HealthData> dataList = healthDataMapper.selectList(
            new QueryWrapper<HealthData>()
                .eq("elder_id", elderId)
        );

        // 如果已存在记录则更新，否则插入新记录
        if (!dataList.isEmpty()) {
            // 更新现有记录
            HealthData existingData = dataList.get(0);
            healthData.setDataId(existingData.getDataId());
            healthDataMapper.updateById1(healthData);
        } else {
            // 插入新记录
            healthDataMapper.insert(healthData);
        }

        // 如果有预警，则发送消息通知并记录到预警日志
        if (!"NORMAL".equals(alertCheckResult.getAlertLevel()) && alertCheckResult.getAlertType() != null) {
            // 构造预警日志
            AlertLog alertLog = AlertLog.builder()
                    .elderId(elderId)
                    .elderName(healthDataDTO.getElderName())
                    .communityId(communityElderMapper.selectCommunityIdByElderId(elderId))
                    .alertType(alertCheckResult.getAlertType())
                    .alertLevel("RED".equals(alertCheckResult.getAlertLevel()) ? 2 : 1) // 1-黄色预警, 2-红色预警
                    .location(healthDataDTO.getLocation())
                    .status("UNRESOLVED") // 未处理状态
                    .createTime(currentTime)
                    .build();

            // 发送到家庭端队列
            rabbitTemplate.convertAndSend(
                RabbitMQConfig.ALERT_EXCHANGE,
                RabbitMQConfig.ALERT_ROUTING_KEY_FAMILY,
                alertLog
            );

            // 发送到社区端队列
            rabbitTemplate.convertAndSend(
                RabbitMQConfig.ALERT_EXCHANGE,
                RabbitMQConfig.ALERT_ROUTING_KEY_COMMUNITY,
                alertLog
            );
        }
    }

    @Override
    public void elderSOS(SosDTO sosDTO) {
        Long currentUserId = UserContext.getUserId();
        System.out.println("当前用户ID：" + currentUserId);
        // 根据用户ID获取用户信息
        User user = userMapper.selectByUserId(currentUserId);
        if (user == null) {
            throw new RuntimeException("未找到对应的用户信息");
        }
        // 根据用户真实姓名查找对应的老人信息
        QueryWrapper<Elder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", user.getRealName());
        Elder elder = communityElderMapper.selectOne(queryWrapper);
        if (elder == null) {
            throw new RuntimeException("未找到对应的老人信息");
        }
        // 获取绑定的社区ID
        String communityId = communityElderMapper.selectCommunityIdByElderId(String.valueOf(elder.getElderId()));
        // 构建预警日志
        String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        AlertLog alertLog = AlertLog.builder()
                .elderId(String.valueOf(elder.getElderId()))
                .elderName(elder.getName())
                .communityId(communityId)
                .alertType("SOS")
                .alertLevel(2) // SOS为红色预警
                .location(sosDTO.getLocation())
                .status("UNRESOLVED") // 未处理状态
                .createTime(currentTime)
                .build();
        // 发送到家庭端队列
        rabbitTemplate.convertAndSend(
                RabbitMQConfig.ALERT_EXCHANGE,
                RabbitMQConfig.ALERT_ROUTING_KEY_FAMILY,
                alertLog
        );
        // 发送到社区端队列
        rabbitTemplate.convertAndSend(
                RabbitMQConfig.ALERT_EXCHANGE,
                RabbitMQConfig.ALERT_ROUTING_KEY_COMMUNITY,
                alertLog
        );
    }

    /**
     * 检查健康数据并确定预警等级
     * @param healthDataDTO 健康数据DTO
     * @return 预警检查结果
     */
    private AlertCheckResult checkHealthData(HealthDataDTO healthDataDTO) {
        AlertCheckResult result = new AlertCheckResult();

        // 心率检查 (正常范围: 60-100)
        Integer heartRate = healthDataDTO.getHeartRate();
        if (heartRate != null) {
            if (heartRate < 50 || heartRate > 120) {
                // 严重异常，红色预警
                result.setAlertLevel("RED");
                result.setAlertType("HEART_RATE");
                result.setAlertContent("心率严重异常: " + heartRate + " 次/分钟");
                return result;
            } else if (heartRate < 60 || heartRate > 100) {
                // 轻度异常，黄色预警
                result.setAlertLevel("YELLOW");
                result.setAlertType("HEART_RATE");
                result.setAlertContent("心率轻度异常: " + heartRate + " 次/分钟");
                return result;
            }
        }

        // 血氧检查 (正常范围: 95%以上)
        Integer bloodOxygen = healthDataDTO.getBloodOxygen();
        if (bloodOxygen != null) {
            if (bloodOxygen < 90) {
                // 严重异常，红色预警
                result.setAlertLevel("RED");
                result.setAlertType("BLOOD_OXYGEN");
                result.setAlertContent("血氧严重异常: " + bloodOxygen + "%");
                return result;
            } else if (bloodOxygen < 95) {
                // 轻度异常，黄色预警
                result.setAlertLevel("YELLOW");
                result.setAlertType("BLOOD_OXYGEN");
                result.setAlertContent("血氧轻度异常: " + bloodOxygen + "%");
                return result;
            }
        }

        // 血压检查 (收缩压正常范围: 90-140，舒张压正常范围: 60-90)
        Integer bloodPressure = healthDataDTO.getBloodPressure();
        if (bloodPressure != null) {
            // 这里简化处理，假设bloodPressure存储的是收缩压
            if (bloodPressure < 90 || bloodPressure > 180) {
                // 严重异常，红色预警
                result.setAlertLevel("RED");
                result.setAlertType("BLOOD_PRESSURE");
                result.setAlertContent("血压严重异常: " + bloodPressure + " mmHg");
                return result;
            } else if (bloodPressure < 100 || bloodPressure > 160) {
                // 轻度异常，黄色预警
                result.setAlertLevel("YELLOW");
                result.setAlertType("BLOOD_PRESSURE");
                result.setAlertContent("血压轻度异常: " + bloodPressure + " mmHg");
                return result;
            }
        }

        // 睡眠质量检查 (正常范围: 假设正常值为7-9小时)
        Integer sleepQuality = healthDataDTO.getSleepQuality();
        if (sleepQuality != null) {
            if (sleepQuality < 3) {
                // 严重不足，红色预警
                result.setAlertLevel("RED");
                result.setAlertType("SLEEP_QUALITY");
                result.setAlertContent("睡眠质量严重不足: " + sleepQuality + " 小时");
                return result;
            } else if (sleepQuality < 6) {
                // 轻度不足，黄色预警
                result.setAlertLevel("YELLOW");
                result.setAlertType("SLEEP_QUALITY");
                result.setAlertContent("睡眠质量不足: " + sleepQuality + " 小时");
                return result;
            }
        }

        // 所有指标正常
        result.setAlertLevel("NORMAL");
        return result;
    }

    /**
     * 预警检查结果内部类
     */
    private static class AlertCheckResult {
        private String alertLevel = "NORMAL";
        private String alertType;
        private String alertContent;

        public String getAlertLevel() {
            return alertLevel;
        }

        public void setAlertLevel(String alertLevel) {
            this.alertLevel = alertLevel;
        }

        public String getAlertType() {
            return alertType;
        }

        public void setAlertType(String alertType) {
            this.alertType = alertType;
        }

        public String getAlertContent() {
            return alertContent;
        }

        public void setAlertContent(String alertContent) {
            this.alertContent = alertContent;
        }
    }
}
